const http = require('http'); // 引入http模块
const fs = require('fs'); // 引入fs模块
const path = require('path'); // 引入path模块
const WebSocket = require('ws'); // 引入WebSocket模块
const chokidar = require('chokidar'); // 引入chokidar模块

const hostname = '127.0.0.1'; // 设置主机名
const port = 3001; // 设置端口号
const WS_PORT = 8081; // 设置WebSocket端口号
const objDirName = path.join(__dirname, '../'); // 设置文件路径

// 创建http服务器
const server = http.createServer((req, res) => {
  let filePath = path.join(objDirName, req.url === '/' ? '/test/index.html' : req.url); // 设置文件路径
  console.log(objDirName, req.url)

  const extname = String(path.extname(filePath)).toLowerCase(); // 获取文件后缀名

  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.gif': 'image/gif',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.ttf': 'application/font-sfnt'
  };

  const contentType = mimeTypes[extname] || 'application/octet-stream'; // 设置文件类型

  fs.readFile(filePath, (error, content) => { // 读取文件

    if (error) {
      if (error.code === 'ENOENT') {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end('Page not found');
      } else {
        res.writeHead(500);
        res.end(`Server Error: ${error.code}`);
      }
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

server.listen(port, hostname, () => { // 启动服务器
  console.log(`Server running at http://${hostname}:${port}/`);
  import('open').then((open) => {
    // 使用open模块
    open.default(`http://${hostname}:${port}`);
    // open.default('https://example.com');
  });
});

// 创建WebSocket服务器
const reloadServer = new WebSocket.Server({ port: WS_PORT });

reloadServer.on('listening', () => {
  console.log(`WebSocket Server is running on port: ${WS_PORT}`);
});

reloadServer.on('connection', (client) => {
  client.on('message', (message) => {
    console.log('Received message:', message);
  });

  client.send('Connected to WebSocket server');
});

// 刷新客户端
function reloadClients () {
  reloadServer.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send('RELOAD');
    }
  });
}

// 创建文件监听器
const watcher = chokidar.watch('.', {
  ignored: /(^|[\/\\])\../, // 忽略以 . 开头的文件和目录
  persistent: true, // 持续监听
  followSymlinks: true, // 跟踪符号链接
  ignoreInitial: false, // 不忽略初始扫描时的事件
  awaitWriteFinish: {
    stabilityThreshold: 500, // 等待文件大小稳定的时间（毫秒）
    pollInterval: 100 // 检查文件大小的间隔（毫秒）
  }
});

watcher.on('change', (path) => {
  console.log(`File ${path} has been changed`);
  reloadClients();
});
